from contextlib import asynccontextmanager
import os
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
import uvicorn
from fastapi import FastAPI
from tortoise import Tortoise
from app.middlewares.auth_middleware import AuthenticationMiddleware
from app.middlewares.exception_handlers import validation_exception_handler
from app.routers.api import api_router
from app.core.config import TORTOISE_ORM
from app.settings import MEDIA_BASE_PATH

@asynccontextmanager
async def lifespan(app: FastAPI):
    try:
        await Tortoise.init(config=TORTOISE_ORM)
        await Tortoise.generate_schemas()
        print("数据库连接成功初始化")
        yield
    except Exception as e:
        print(f"数据库初始化错误: {e}")
        raise
    finally:
        await Tortoise.close_connections()
        print("应用关闭，数据库连接已关闭")

app = FastAPI(lifespan=lifespan)



# 挂载静态资源目录
app.mount("/media", StaticFiles(directory=os.path.join(MEDIA_BASE_PATH, "media")), name="media")

# 添加认证中间件
app.add_middleware(AuthenticationMiddleware)
# 添加验证异常处理器
app.add_exception_handler(RequestValidationError, validation_exception_handler)
URL_IMG = os.path.join(MEDIA_BASE_PATH, "media","avatar_img")
app.mount("/avatar_img", StaticFiles(directory=URL_IMG), name="avatar_img")

# 包含API路由
app.include_router(api_router, prefix="/api")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)